package com.kc.gb.device.controller;

import cn.hutool.core.net.NetUtil;
import com.kc.gb.base.dto.DeviceType;
import com.kc.gb.base.dto.Result;
import com.kc.gb.device.common.dto.I18NException;
import com.kc.gb.device.common.enums.ErrorCode;
import com.kc.gb.device.common.interfaces.IHardware;
import com.kc.gb.device.common.properties.DeviceConfiguration;
import com.kc.gb.device.common.properties.DeviceProperties;
import com.kc.gb.device.common.utils.I18NHelper;
import com.kc.gb.device.common.utils.SpringHelper;
import com.kc.gb.device.service.ConfigAdminService;
import com.kc.gb.device.service.support.dto.DeviceReadWriteProperty;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/station/device/properties")
public class ConfigAdminController {

    @Resource
    ConfigAdminService iConfigAdminService;

    @GetMapping(path = "/get")
    private Result<?> getProperties() {
        try {
            DeviceReadWriteProperty property = new DeviceReadWriteProperty();
            DeviceProperties diskProperty = DeviceConfiguration.getDeviceProperties();
            BeanUtils.copyProperties(diskProperty,property);
            String localIP = NetUtil.getLocalhostStr();
            property.setLocalIP(localIP);
            String language = I18NHelper.getDefaultLocale().toLanguageTag();
            property.setLanguage(language);
            return Result.success(property);
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    @PostMapping(path = "/save")
    private Result<?> saveProperties(@RequestBody DeviceReadWriteProperty property) {
        try {
            DeviceProperties properties = new DeviceProperties();
            BeanUtils.copyProperties(property,properties);
            iConfigAdminService.flush(properties);
            return Result.success(property);
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    @GetMapping(path = "/getConnectResult/{type}")
    private Result<?> getConnectResult(@PathVariable DeviceType type) {
        try {
            IHardware beans = SpringHelper.getApplicationContext().getBean(type.name(),IHardware.class);
            if(!beans.isEnabled()){
                throw new I18NException(ErrorCode.HARDWARE_NOT_ENABLED);
            }
            return beans.isConnected();
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }
}
